package com.ropeok.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.*;

public class c3p0Util {
    private static ComboPooledDataSource dataSource=new ComboPooledDataSource();

    //线程存Connection对象
    private static ThreadLocal<Connection> tol=new ThreadLocal<Connection>();

    public static Connection getConnection() {
        Connection connection = tol.get();
        try {
             connection = dataSource.getConnection();
        }catch (SQLException e){
            e.printStackTrace();
        }
        tol.set(connection);
        return connection;
    }

    public static void close(PreparedStatement ps, Connection con, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        if (ps!=null){
            try {
                ps.close();
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        if (con!=null){
            try {
                con.close();
                tol.remove();
            }catch (SQLException ex){
                throw new RuntimeException("close Connection fail");
            }
        }
    }
}
